package com.train.mgr.modules.biz.controller;

import com.train.common.enums.TplFileEnum;
import com.train.common.exception.BizException;
import com.train.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@RestController
@Slf4j
@RequestMapping("/tpl_download")
@Api( tags = "EXCEL模版下载")
@RequiredArgsConstructor
public class DownloadTplController {

    @GetMapping("/xls/{code}")
    @ApiOperation("模版下载")
    public void downloadXlsTmp(@PathVariable(name = "code") String code,
                               HttpServletResponse response,HttpServletRequest request)  {
        String filePath = TplFileEnum.getFilename(code);
        log.info("downloadXlsTmp filePath:{}",filePath);
        if(StringUtils.isEmpty(filePath)){
            throw new BizException("编码未定义，模版下载失败");
        }
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        try{
            /** 将文件名称进行编码 */
            response.setHeader("content-disposition", "attachment;filename=" + 	 URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("content-type:octet-stream");
            /** 读取服务器端模板文件*/
            InputStream inputStream = DownloadTplController.class.getResourceAsStream(filePath);

            /** 将流中内容写出去 .*/
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            inputStream.close();
            outputStream.close();
        }catch (Exception ex){
            log.error("error:",ex);
        }
    }
}
